const _ = require('lodash');

module.exports = function(db) {
  const collection = db.collection('statistics-arena-users');
  const indexes = [
    { key: { uid: 1 }, name: 'uid_1' },
    { key: { arena_room_id: 1 }, name: 'arena_room_id_1' },
    { key: { season_id: 1 }, name: 'season_id_1' },
    { key: { date: 1 }, name: 'date_1' },
  ];

  collection.createIndexes(indexes);

  return {
    name: 'statisticsArenaUsers',
    updateArenaUser: function(selector, update, options) {
      return collection.updateOne(selector, update, {
        upsert: true,
        ...options,
      });
    },

    // 统计某一天在某个竞技场房间玩的人
    findPlayedUsersInSeasonRoom: function(season_id, arena_room_id, date) {
      return collection.distinct('uid', { season_id, arena_room_id, date });
    },

    // 统计在竞技场某个赛季总参与人数
    findPlayedUsersInSeason: function(season_id) {
      return collection.distinct('uid', { season_id });
    },

    findPlayedUsers: function(date) {
      return collection.distinct('uid', { date });
    },

    findPlayedRounds: function(date) {
      return collection
        .aggregate([
          { $match: { date } },
          {
            $group: {
              _id: '$date',
              played_rounds: { $sum: '$played_rounds' },
            },
          },
        ])
        .toArray();
    },
  };
};
